<?php include_once 'header.php'; ?>
<aside class="right-side">
    <section class="content-header">
        <h1>
            Inventory
            <small>Category Management</small>
        </h1>
        <ol class="breadcrumb">
            <li><a href="#"><i class="fa fa-cubes"></i> Inventory</a></li>
            <li class="active">Category</li>
        </ol>
    </section>
    <section class="content">
        <div class="row">
            <div class="col-md-5">
                <div class="box box-primary">
                    <div class="box-header">
                        <div class="col-sm-7 col-md-7 col-lg-7">
                            <h3 class="box-title" id="box-title"><i class="fa fa-list"></i> Add Category Name</h3>
                        </div>
                        <div class="col-sm-5 col-md-5 col-lg-5" style="padding-left:5px;padding-top:5px;text-align: right;padding-right:5px;">
                            <button id="parent-category-btn" type="submit" class="btn btn-warning" data-toggle="modal" data-target="#myModal">
                                <i class="fa fa-plus-square"></i> &nbsp;Top Level Category
                            </button>
                        </div>
                    </div>
                    <form id="category-form" role="form">
                        <div class="box-body">
                            <div class="form-group">
                                <label for="exampleInputEmail1">Name</label>
                                <input type="hidden" id="category-id" name="category-id">
                                <input type="text" class="form-control" id="category-name" name="category-name"
                                       placeholder="Enter Category Name" data-validation="required"
                                       data-validation-error-msg="Please enter category name.">
                            </div>
                            <div class="form-group">
                                <label for="exampleInputEmail1">Category</label>
                                <select id="parent-category" name="parent-category" class="form-control" data-validation="required" data-validation-error-msg="Please select category name.">
                                </select>
                            </div>
                        </div>
                        <div class="box-footer">
                            <button id="submit-category" type="submit" class="btn btn-primary ladda-button"
                                    data-style="slide-right">Save
                            </button>
                        </div>
                    </form>
                </div>
            </div>
            <div class="col-md-7">
                <div class="box box-primary">
                    <table class="table table-condensed">
                        <thead>
                        <tr>
                            <th style="width: 5%">#</th>
                            <th style="width: 50%">Category Name</th>
                            <th style="width: 20%">Date Created</th>
                            <th style="width: 25%;text-align: center;">Action</th>
                        </tr>
                        </thead>
                        <tbody id="category-list">
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </section>
</aside>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close close-product-model" data-dismiss="modal">
                    <span aria-hidden="true">&times;</span>
                    <span class="sr-only">Close</span>
                </button>
                <h4 class="modal-title" id="myModalLabel"><i class="fa fa-list"></i> Top Level Categories</h4>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-sm-12 col-md-12 col-lg-12">
                        <form class="form-horizontal" id="top-category-form" role="form">
                            <div class="col-sm-10 col-md-10 col-lg-10">
                                <div class="form-group">
                                    <input type="hidden" id="top-category-id" name="top-category-id">
                                    <input type="text" class="form-control" id="top-category-name" name="category-name"
                                           placeholder="Enter Category Name" data-validation="required"
                                           data-validation-error-msg="Please enter category name.">
                                </div>
                            </div>
                            <div class="col-sm-2 col-md-2 col-lg-2">
                                <button id="top-category-submit" type="submit" class="btn btn-primary ladda-button"
                                        data-style="slide-right">Save
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
                <div class="row">
                    <div id="top-level-category-tbl" class="col-sm-12 col-md-12 col-lg-12">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include 'footer.php'; ?>
<script>

    $(document).ready(function () {
        $.get("getCategory", function (response) {
            if (!response.error) {
                populateCategoryTable(response.data);
            } else {
                errorAlert(response.errorMessage);
            }
        });


        $("#category-name").keydown(function () {
            $(this).parent().removeClass('has-success');
        });

        $('body').on('click', 'button.edit-category', function () {
            var button = Ladda.create(this);
            button.start();
            var id = getElementId($(this).attr("id"));
            $.get("getCategory/" + id,function (response) {
                if (!response.error) {
                    if(response.data.parent == null){
                        $("#top-category-id").val(response.data.id);
                        $("#top-category-name").val(response.data.name);
                        $('#myModal').modal('show');
                    }else{
                        $("#category-id").val(response.data.id);
                        $("#category-name").val(response.data.name);
                        $("#parent-category").val(response.data.parent.id);
                    }
                } else {
                    errorAlert(response.errorMessage);
                }
            }).always(function () {
                    button.stop();
                });
        });

        $('body').on('click', 'button.delete-category', function () {
            var button = Ladda.create(this);
            button.start();
            var id = getElementId($(this).attr("id"));
            $.get("deleteCategory/" + id,function (response) {
                if (!response.error) {
                    $("#category-id").val("");
                    $("#category-name").val("");
                    populateCategoryTable(response.data);
                } else {
                    errorAlert(response.errorMessage);
                }
            }).always(function () {
                    button.stop();
                });
        });

        $(".close-product-model").click(function(){
            $("#top-category-id").val("");
            $("#top-category-name").val("");
        });
    });

    $.validate({
        form: '#category-form',
        validateOnBlur: false,
        onError: function () {
            $("#status").text("");
            return false;
        },
        onSuccess: function ($form) {
            var submitButton = Ladda.create(document.querySelector('#submit-category'));
            submitButton.start();
            var handler = $.post("addEditCategory", $("#category-form").serialize(), function (response) {
                if (!response.error) {
                    populateCategoryTable(response.data);
                    $("#category-id").val("");
                    $form.resetForm();
                } else {
                    errorAlert(response.errorMessage);
                }
            })
                .error(function (error) {
                    errorAlert("Please refresh page and try again, if Problem persist contact support team.")
                })
                .always(function () {
                    submitButton.stop();
                });
            return false;
        }
    });

    function populateCategoryTable(jsonArray) {
        $("#category-list").html("");
        $("#parent-category").html("");
        for (var i = 0; i < jsonArray.length; i++) {
            if(jsonArray[i].parent == null){
                $("#category-list").append("<tr style='background-color: lavender;'><td><i class='fa fa-sort-down'></i></td><td>" + jsonArray[i].name + "</td><td>" + moment(jsonArray[i].dateCreate.date).format('lll') + "</td><td style='text-align: center;'><button id='category_" + jsonArray[i].id + "' type='button' class='btn btn-default table-action-button ladda-button edit-category edit-parent-category' data-style='slide-right'><i class='fa fa-pencil'></i></button> &nbsp;&nbsp;<button id='category_" + jsonArray[i].id + "' type='button' class='btn btn-danger table-action-button ladda-button delete-category' data-style='slide-right'><i class='fa fa-trash-o'></i></button></td></tr>");
                $("#parent-category").append("<option value="+ jsonArray[i].id +">"+ jsonArray[i].name +"</option>");
                $count = 0;
                for(var j = 0; j < jsonArray.length; j++){
                    if(jsonArray[j].parent != null && jsonArray[j].parent.id == jsonArray[i].id){
                        $count = $count + 1;
                        $("#category-list").append("<tr><td>" + $count + "</td><td>" + jsonArray[j].name + "</td><td>" + moment(jsonArray[i].dateCreate.date).format('lll') + "</td><td style='text-align: center;'><button id='category_" + jsonArray[j].id + "' type='button' class='btn btn-default table-action-button ladda-button edit-category' data-style='slide-right'><i class='fa fa-pencil'></i></button> &nbsp;&nbsp;<button id='category_" + jsonArray[j].id + "' type='button' class='btn btn-danger table-action-button ladda-button delete-category' data-style='slide-right'><i class='fa fa-trash-o'></i></button></td></tr>");
                    }
                }
            }

        }
    }

    $.validate({
        form: '#top-category-form',
        validateOnBlur: false,
        onError: function () {
            return false;
        },
        onSuccess: function ($form) {
            var submitButton = Ladda.create(document.querySelector('#top-category-submit'));
            submitButton.start();
            var handler = $.post("addEditTopCategory", $("#top-category-form").serialize(), function (response) {
                if (!response.error) {
                    $("#top-category-id").val("");
                    populateCategoryTable(response.data);
                    $form.resetForm();
                } else {
                    errorAlert(response.errorMessage);
                }
            })
                .error(function (error) {
                    errorAlert("Please refresh page and try again, if Problem persist contact support team.")
                })
                .always(function () {
                    submitButton.stop();
                });
            return false;
        }
    });
</script>